<script setup>
import {ref, computed, onMounted} from 'vue';
import { useUserStore } from '@/stores/user';
import {addGoodsAPI, getCategoryListAPI,uploadMainImgAPI,deleteImgAPI} from '@/api/Goods.js';
import {ElMessage} from 'element-plus';

const store = useUserStore();
const userId = store.UserId; // 假设 userId 已经在 store 中存储

// 表单数据和商品类型切换
const goodsData = ref({
  categoryId: null,
  userId,
  name: '',
  price: null,
  weight: null,
  type: 1, // 默认新商品
  brokenRate: null,
  description: '',
  epFactor: null,
  image: '',
  nums: null,
});

// 分类列表用于下拉选择框
const categories = ref([]);

// 获取分类数据
const fetchCategories = async () => {
  try {
    const {data} = await getCategoryListAPI(goodsData.value.type);
    categories.value = data.data;
  } catch (error) {
    ElMessage.error('获取分类失败');
  }
};

// 监听商品类型切换并重新获取分类数据
onMounted(fetchCategories);

// 动态显示 brokenRate（仅用于二手商品）
const showBrokenRate = computed(() => goodsData.value.type === 2);

// 提交表单
const submitForm = async () => {
  try {
    await addGoodsAPI(goodsData.value);
    ElMessage.success('商品添加成功');
    goodsData.value = {};
  } catch (error) {
    ElMessage.error('添加商品失败');
  }
};

const handleFileUpload = async (file) => {
  const formData = new FormData();
  formData.append('image', file); // 确保与后端一致

  try {
    const response = await uploadMainImgAPI(formData);
    goodsData.value.image = response.data.data; // 假设后端返回图片URL为 `data.url`
  } catch (error) {
    console.error('图片上传失败', error);
  }
};
// 清除图片
const clearImage = async () => {
  const response = await deleteImgAPI(goodsData.value.image);
  if(response.data.code === 200){
    ElMessage.success('图片删除成功');
    goodsData.value.image = '';
  }
  else {
    ElMessage.error('图片删除失败');
  }
};

</script>

<template>
  <div>
    <h1>发布商品</h1>

    <!-- 新商品和二手商品切换 -->
    <div style="margin-bottom: 20px; text-align: center;">
      <el-radio-group v-model="goodsData.type" @change="fetchCategories">
        <el-radio :label="1">新商品</el-radio>
        <el-radio :label="2">二手商品</el-radio>
      </el-radio-group>
    </div>

    <!-- 商品详细信息表单，宽度设置为500px -->
    <el-form :model="goodsData" label-width="100px" @submit.prevent="submitForm" style="width: 500px; margin: 0 auto;">
      <!-- 分类下拉选择框 -->
      <el-form-item label="分类">
        <el-select v-model="goodsData.categoryId" placeholder="选择分类">
          <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
          />
        </el-select>
      </el-form-item>

      <!-- 商品详细信息表单输入框 -->
      <el-form-item label="商品名称">
        <el-input v-model="goodsData.name" placeholder="请输入商品名称"/>
      </el-form-item>
      <el-form-item label="价格">
        <el-input v-model="goodsData.price" placeholder="请输入价格" type="number"/>
      </el-form-item>
      <el-form-item label="重量">
        <el-input v-model="goodsData.weight" placeholder="请输入重量" type="number"/>
      </el-form-item>

      <!-- 二手商品专属的破损率 -->
      <el-form-item label="破损率" v-if="showBrokenRate">
        <el-input v-model="goodsData.brokenRate" placeholder="请输入破损率" type="number"/>
      </el-form-item>

      <el-form-item label="描述">
        <el-input type="textarea" v-model="goodsData.description" placeholder="请输入描述"/>
      </el-form-item>

      <!-- EP因子下拉选择框，显示文字 -->
      <el-form-item label="EP因子">
        <el-select v-model="goodsData.epFactor" placeholder="选择EP因子">
          <el-option label="不可循环材料" :value="1" />
          <el-option label="部分环保材料" :value="1.1" />
          <el-option label="完全环保材料" :value="1.2" />
        </el-select>
      </el-form-item>

        <!-- 图片选择与上传 -->
        <el-form-item label="商品主图">
          <!-- 上传和清除按钮 -->
            <el-upload
                accept="image/*"
                :show-file-list="false"
                :before-upload="handleFileUpload"
            >
              <el-button type="primary">点击选择图片</el-button>
            </el-upload>
            <el-button v-if="goodsData.image" @click="clearImage" type="danger" style="margin-left: 10px;">
              清除图片
            </el-button>

          <!-- 图片预览 -->
          <img v-if="goodsData.image" :src="goodsData.image" alt="预览图片" style="width:300px; margin-top: 10px;" />
        </el-form-item>

      <el-form-item label="数量">
        <el-input v-model="goodsData.nums" placeholder="请输入数量" type="number"/>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm">添加商品</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>




<style scoped>
h1 {
  text-align: center;
  margin-bottom: 20px;
}
</style>
